package com.ddwl.goods.service.bargain;

import cn.hutool.core.util.StrUtil;
import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.constant.GoodsEnum;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.feign.api.ShopApi;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.goods.dao.bargain.BargainActivityDao;
import com.ddwl.goods.dao.bargain.BargainSkuDao;
import com.ddwl.goods.model.bargain.BargainActivity;
import com.ddwl.goods.model.bargain.BargainSku;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.goods.bargain.*;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.goods.bargain.BargainActivityVo;
import com.ddwl.schema.vo.shop.ShopVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author hemiaojun
 * @Date 2020/10/23 17:23
 */
@Service
public class BargainActivityService {

    @Resource
    private BargainActivityDao bargainActivityDao;
    @Resource
    private BargainSkuDao bargainSkuDao;
    @Resource
    private ShopApi shopApi;

    @Transactional(rollbackFor = Exception.class)
    public void add(BargainActivityAddBo bo, String product) {
        if (BaseEnum.ProductEnum.WBM.getName().equals(product)) {
            ParamException.isTrue((!BaseEnum.StatusEnum.ENABLE.getCode().equals(bo.getLogisticsTag()) && !BaseEnum.StatusEnum.ENABLE.getCode().equals(bo.getSelfMentionTag()) && !BaseEnum.StatusEnum.ENABLE.getCode().equals(bo.getLocalDeliveryTag())), "至少选择一种配送方式");
        }
        if (StrUtil.isEmpty(bo.getShopId())) {
            bo.setShopId(getDefaultShopId());
        }
        BargainActivity entity = BeanConverUtils.convertBean(bo, BargainActivity.class);
        entity.setId(UUIDGenerator.getShortUUID());
        validation(entity);
        setStock(entity, bo.getBargainSkuAddBo().getChopStockList());
        entity.setStatus(GoodsEnum.BargainActivityStatusEnum.PROCESSING.getCode());
        bargainActivityDao.insert(entity);
        addBargainSku(bo.getBargainSkuAddBo(), entity.getId(),bo.getItemId());
    }

    public BargainActivityVo getById(String id) {
        return BeanConverUtils.convertBean(bargainActivityDao.selectByPrimaryKey(id),BargainActivityVo.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(BargainActivityUpdateBo bo) {
        ParamException.isTrue((!BaseEnum.StatusEnum.ENABLE.getCode().equals(bo.getLogisticsTag()) && !BaseEnum.StatusEnum.ENABLE.getCode().equals(bo.getSelfMentionTag()) && !BaseEnum.StatusEnum.ENABLE.getCode().equals(bo.getLocalDeliveryTag())),"至少选择一种配送方式" );
        BargainActivityVo baVo = getById(bo.getId());
        ParamException.isTrue(Instant.now().compareTo(baVo.getStartTime()) > 0, "活动一旦开始之后，不允许修改");
        BargainActivity entity = BeanConverUtils.convertBean(bo, BargainActivity.class);
        validation(entity);
        setStock(entity, bo.getBargainSkuAddBo().getChopStockList());
        bargainActivityDao.updateByPrimaryKeySelective(entity);
        bargainSkuDao.deleteByActivityId(bo.getId());
        addBargainSku(bo.getBargainSkuAddBo(), entity.getId(),bo.getItemId());
    }

    private void setStock(BargainActivity entity, List<Integer> chopStockList) {
        Integer sumStock = 0;
        for (Integer stock : chopStockList) {
            sumStock += stock;
        }
        entity.setSumStock(sumStock);
        entity.setSurplusStock(sumStock);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        bargainActivityDao.deleteById(id);
        bargainSkuDao.updateDflagByActivityId(id);
    }

    public PageVo<BargainActivityVo> page(PageBo<BargainActivityPageBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(), pageBo.isAsc()));
        PageInfo<BargainActivityVo> info=new PageInfo<>(bargainActivityDao.getList(pageBo.getParam()));
        return new PageVo<>(info.getTotal(), pageBo.getPage(), pageBo.getPageSize(), info.getList());
    }

    private void addBargainSku(BargainSkuAddBo bargainSkuAddBo, String activityId, String itemId) {
        List<String> barcodeList=bargainSkuAddBo.getBarcodeList();
        List<Integer> chopStockList = bargainSkuAddBo.getChopStockList();
        if (!CollectionUtils.isEmpty(barcodeList) && !CollectionUtils.isEmpty(chopStockList)) {
            List<BargainSku> list = new ArrayList<>();
            for (int i = 0; i < barcodeList.size(); i++) {
                BargainSku bs = new BargainSku();
                bs.setActivityId(activityId);
                bs.setItemId(itemId);
                bs.setBarcode(barcodeList.get(i));
                bs.setChopStock(chopStockList.get(i));
                list.add(bs);
            }
            bargainSkuDao.insertList(list);
        }
    }

    public void updateActivity(BargainActivity ba) {
        bargainActivityDao.updateByPrimaryKeySelective(ba);
    }

    public void openOrClose(BargainActivityStatusBo bo) {
        BargainActivity entity = BeanConverUtils.convertBean(bo, BargainActivity.class);
        bargainActivityDao.updateByPrimaryKeySelective(entity);
    }

    private void validation(BargainActivity entity){
        ParamException.isTrue((null != entity.getThresholdPrice() && entity.getThresholdPrice().compareTo(entity.getItemPrice()) >= 0), "底价不能大于等于商品原价");
        ParamException.isTrue((null != entity.getFirstMoney() && entity.getFirstMoney().compareTo(entity.getItemPrice()) > 0),"首刀金额不能大于商品原价");
        if (GoodsEnum.BargainChopTypeEnum.RANDOM.getCode().equals(entity.getChopType())) {
            ParamException.isTrue((null==entity.getRandomMin()||null==entity.getRandomMax()),"随机金额不能为空");
        }
        if (GoodsEnum.ActivityPlatformEnum.CONSOLE.getCode().equals(entity.getPlatform()) && entity.getThresholdPrice().compareTo(BigDecimal.ZERO) > 0) {
            ParamException.isTrue(null == entity.getThresholdRandomMin() || entity.getThresholdRandomMin().compareTo(BigDecimal.ZERO) < 0, "超出底价后的随机最小金额不能为空且必须大于0");
            ParamException.isTrue(null == entity.getThresholdRandomMax() || entity.getThresholdRandomMax().compareTo(BigDecimal.ZERO) < 0, "超出底价后的随机最大金额不能为空且必须大于0");
            ParamException.isTrue(entity.getThresholdRandomMax().compareTo(entity.getThresholdRandomMin()) < 0, "超出底价后的随机最大金额必须大于随机最小金额");
        }
        if (GoodsEnum.BargainChopTypeEnum.FIXED.getCode().equals(entity.getChopType())) {
            ParamException.isNull(entity.getChopNum(),"帮砍人数不能为空");
        }
    }

    private String getDefaultShopId(){
        ShopVo shopVo = shopApi.getDefaultShopForApi().getResult();
        ParamException.isNull(shopVo, "店铺信息不存在");
        return shopVo.getId();
    }

    public PageVo<BargainActivityVo> merchantPage(PageBo<BoostActivityPageBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(), pageBo.isAsc()));
        PageInfo<BargainActivityVo> info=new PageInfo<>(bargainActivityDao.getMerchantList(pageBo.getParam()));
        return new PageVo<>(info.getTotal(), pageBo.getPage(), pageBo.getPageSize(), info.getList());
    }


}
